package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import play.data.validation.Required;
import play.db.jpa.Model;

/**
 * UnregisteredEmail entity creates an UnregisteredEmail
 * 
 * @author Sara Assem khalil
 */
@Entity
public class UnRegisteredEmail extends Model {
	/**
	 * the email that is being added to the system
	 * 
	 * @author Sara Assem khalil
	 */
	@Required
	public String email;
	/**
	 * the email can have a list of invitations
	 * 
	 * @author Sara Assem khalil
	 */

	@OneToMany(mappedBy = "email")
	public List<UnregisteredInvitation> invitations;

	/**
	 * the constructor takes only on parameter which is the email
	 * 
	 * @param email
	 * 
	 * @author Sara Assem khalil
	 */

	public UnRegisteredEmail(String email) {
		this.email = email;
		this.invitations = new ArrayList<UnregisteredInvitation>();
	}

	/**
	 * checks whether the email givin as paramater already exists in the list of
	 * unregistered users or not
	 * 
	 * 
	 * @param String
	 *            unregisteredemail that is neeeded for the check
	 * @return boolean whether the email givin as paramater already exists in
	 *         the list of unregistered users or not
	 *         @author Sara Assem khalil
	 */
	public static boolean compareEmail(String unregisteredemail) {
		List<UnRegisteredEmail> emails = UnRegisteredEmail.findAll();
		if (emails.size() >= 0) {

			for (int i = 0; i < emails.size(); i++) {

				if (emails.get(i).email.equalsIgnoreCase(unregisteredemail)) {
					return true;
				}

			}

		}
		return false;
	}

	/**
	 * moves the invitation of the unregisteredEmail to teh user created by the
	 * same email
	 * 
	 * @param User
	 *            user the user created
	 *            
	 * @author Sara Assem khalil
	 */
	public void moveInivtations(User user) {

		for (int i = 0; i < invitations.size(); i++) {
			Invitation invitation = new Invitation(user,
					invitations.get(i).message, invitations.get(i).type,
					invitations.get(i).organizationId);

			user.invitations.add(invitation);

			user.save();
			invitations.get(i).delete();
		}

	}
}
